package com.lz.gmall.item.controller;

import com.lz.gmall.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

//测试代码
@RestController
@RequestMapping("/redisson")
@Slf4j
public class RedissonClientController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping(value = "/Lock")
    public Result testLock01() throws InterruptedException {

        // 加锁
        RLock lock = redissonClient.getLock("redisson-lock");

        boolean b = lock.tryLock();
        if (b){
            try {
                try {
                    log.info("线程{}获取到了分布式锁，执行业务操作开始..." , Thread.currentThread().getId());
                    TimeUnit.SECONDS.sleep(10);
                    log.info("线程{}获取到了分布式锁，执行业务操作结束..." , Thread.currentThread().getId());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }finally {
                lock.unlock();
            }
        }else {
            log.info("线程{}没有获取到分布式锁" , Thread.currentThread().getId());
        }
        // 返回结果
        return Result.ok() ;

    }

}
